<template>
  <el-dialog :title="operateMaterial === 'add' ? '新建图文' : '修改图文'" :before-close="dialogNewsClose"
    :close-on-click-modal="false" v-model="dialogNewsVisible" :destroy-on-close="true" width="1000px" top="20px">
    <div v-loading="addMaterialLoading">
      <div style="display: flex;align-items: center;">
        <div>
          <div class="digest" style="display: flex;align-items: center;">
            <div style="display: flex;align-items: center;">
              <div class="input-tt" style="width: 60px;">标题：</div>
              <el-input v-model="articlesAdd.title" style="width: 200px;" placeholder="请输入标题"></el-input>
            </div>
            <div style="display: flex;align-items: center;margin-left: 20px;">
              <div class="input-tt" style="width: 60px;">作者：</div>
              <el-input v-model="articlesAdd.author" style="width: 200px;" placeholder="请输入作者"></el-input>
            </div>
          </div>
          <div style="display: flex;align-items: center;margin-top: 10px;">
            <div class="input-tt" style="width: 60px;">摘要：</div>
            <el-input style="" v-model="articlesAdd.brief" :rows="3" type="textarea" placeholder="请输入摘要"
              maxlength="120"></el-input>
          </div>
        </div>
        <div style="margin-left: 20px;">
          <div class="input-tt">封面图片：</div>
          <img v-if="articlesAdd.cap != null && articlesAdd.cap != ''" style="width: 100px;height: 100px;"
            :src="'/api/' + articlesAdd.cap" />

          <div class="thumb-but">
            <wx-file-upload action="/api/admin/sys-file/upload2" :uploadData="uploadData" @success="handleImageChange"
              @remove="handleRemoveImageChange"></wx-file-upload>
          </div>
        </div>
      </div>
      <!--富文本编辑器组件-->
      <el-row>
        <ckeditor v-if="isLayoutReady" v-model="articlesAdd.content" :editor="editor" @ready="onReady"
          :config="config" />
        <!-- <editor v-model:get-html="articlesAdd.content" style="margin-top: 20px" uploadFileUrl="/admin/sys-file/upload2"
          bucketName="homepage" width="960px" height="500px"></editor> -->
      </el-row>
      <br />

    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogNewsVisible = false">{{ $t('common.cancelButtonText') }}</el-button>
        <el-button type="primary" @click="onSubmit">{{ $t('common.confirmButtonText') }}</el-button>
      </span>
    </template>
  </el-dialog>

  <wx-material-select ref="WxMaterialSelectRef"></wx-material-select>
</template>

<script setup lang="ts" name="addNewsform">
import axios from 'axios'
import { Session } from '/@/utils/storage';
import { useMessageBox } from '/@/hooks/message';
import { addObj, getObj } from "/@/api/information/news";
import {
  ClassicEditor,
  AccessibilityHelp,
  Autoformat,
  AutoImage,
  AutoLink,
  Autosave,
  Bold,
  Code,
  CodeBlock,
  Essentials,
  FontBackgroundColor,
  FontColor,
  FontFamily,
  FontSize,
  GeneralHtmlSupport,
  Heading,
  HtmlEmbed,
  ImageBlock,
  ImageCaption,
  ImageInline,
  ImageInsert,
  ImageInsertViaUrl,
  ImageResize,
  ImageStyle,
  ImageTextAlternative,
  ImageToolbar,
  ImageUpload,
  Italic,
  Link,
  LinkImage,
  List,
  ListProperties,
  Paragraph,
  PasteFromOffice,
  SelectAll,
  ShowBlocks,
  SimpleUploadAdapter,
  SpecialCharacters,
  SpecialCharactersArrows,
  SpecialCharactersCurrency,
  SpecialCharactersEssentials,
  SpecialCharactersLatin,
  SpecialCharactersMathematical,
  SpecialCharactersText,
  Strikethrough,
  Subscript,
  Superscript,
  Table,
  TableCaption,
  TableCellProperties,
  TableColumnResize,
  TableProperties,
  TableToolbar,
  TextTransformation,
  Underline,
  Undo
} from 'ckeditor5';
import translations from 'ckeditor5/translations/zh-cn.js';
import 'ckeditor5/ckeditor5.css';
import MyUploadAdapter from "./MyUploadAdapter.js";
import { log } from 'console';
import { includes, result } from 'lodash';
const WxMaterialSelect = defineAsyncComponent(() => import('/@/components/Wechat/wx-material-select/main.vue'));
const WxFileUpload = defineAsyncComponent(() => import('/@/components/Wechat/fileUpload/index.vue'));
const WxMaterialSelectRef = ref();
const dialogNewsVisible = ref(false);
const operateMaterial = ref('add');
const addMaterialLoading = ref(false);
const isLayoutReady = ref(false);
const config = ref({
  toolbar: {
    items: [
      'undo',
      'redo',
      '|',
      'showBlocks',
      'selectAll',
      '|',
      'heading',
      '|',
      'fontSize',
      'fontFamily',
      'fontColor',
      'fontBackgroundColor',
      '|',
      'bold',
      'italic',
      'underline',
      'strikethrough',
      'subscript',
      'superscript',
      'code',
      '|',
      'specialCharacters',
      'link',
      'insertImage',
      'insertTable',
      'codeBlock',
      'htmlEmbed',
      '|',
      'bulletedList',
      'numberedList',
      '|',
      'accessibilityHelp'
    ],
    shouldNotGroupWhenFull: true
  },
  plugins: [
    AccessibilityHelp,
    Autoformat,
    AutoImage,
    AutoLink,
    Autosave,
    Bold,
    Code,
    CodeBlock,
    Essentials,
    FontBackgroundColor,
    FontColor,
    FontFamily,
    FontSize,
    GeneralHtmlSupport,
    Heading,
    HtmlEmbed,
    ImageBlock,
    ImageCaption,
    ImageInline,
    ImageInsert,
    ImageInsertViaUrl,
    ImageResize,
    ImageStyle,
    ImageTextAlternative,
    ImageToolbar,
    ImageUpload,
    Italic,
    Link,
    LinkImage,
    List,
    ListProperties,
    Paragraph,
    PasteFromOffice,
    SelectAll,
    ShowBlocks,
    SimpleUploadAdapter,
    SpecialCharacters,
    SpecialCharactersArrows,
    SpecialCharactersCurrency,
    SpecialCharactersEssentials,
    SpecialCharactersLatin,
    SpecialCharactersMathematical,
    SpecialCharactersText,
    Strikethrough,
    Subscript,
    Superscript,
    Table,
    TableCaption,
    TableCellProperties,
    TableColumnResize,
    TableProperties,
    TableToolbar,
    TextTransformation,
    Underline,
    Undo
  ],
  fontFamily: {
    supportAllValues: true
  },
  fontSize: {
    options: [10, 12, 14, 'default', 18, 20, 22],
    supportAllValues: true
  },
  heading: {
    options: [
      {
        model: 'paragraph',
        title: 'Paragraph',
        class: 'ck-heading_paragraph'
      },
      {
        model: 'heading1',
        view: 'h1',
        title: 'Heading 1',
        class: 'ck-heading_heading1'
      },
      {
        model: 'heading2',
        view: 'h2',
        title: 'Heading 2',
        class: 'ck-heading_heading2'
      },
      {
        model: 'heading3',
        view: 'h3',
        title: 'Heading 3',
        class: 'ck-heading_heading3'
      },
      {
        model: 'heading4',
        view: 'h4',
        title: 'Heading 4',
        class: 'ck-heading_heading4'
      },
      {
        model: 'heading5',
        view: 'h5',
        title: 'Heading 5',
        class: 'ck-heading_heading5'
      },
      {
        model: 'heading6',
        view: 'h6',
        title: 'Heading 6',
        class: 'ck-heading_heading6'
      }
    ]
  },
  htmlSupport: {
    allow: [
      {
        name: /^.*$/,
        styles: true,
        attributes: true,
        classes: true
      }
    ]
  },
  image: {
    toolbar: [
      'toggleImageCaption',
      'imageTextAlternative',
      '|',
      'imageStyle:inline',
      'imageStyle:wrapText',
      'imageStyle:breakText',
      '|',
      'resizeImage'
    ]
  },
  SimpleUploadAdapter: {
    uploadUrl: '/ck-image-upload/upload?moreUrls=1', // 上传图像服务器地址（可能需要解决跨域问题），moreUrls=1 可生成多链接图像
    withCredentials: true, // 启用 XMLHttpRequest.withCredentials 属性
    headers: {
      'Accept-Api-Key': 'ASK_D_FF', // 请求头设置来验证身份的（自己定义属性）
    }

  },
  initialData:
    '',
  language: 'zh-cn',
  link: {
    addTargetToExternalLinks: true,
    defaultProtocol: 'https://',
    decorators: {
      toggleDownloadable: {
        mode: 'manual',
        label: 'Downloadable',
        attributes: {
          download: 'file'
        }
      }
    }
  },
  list: {
    properties: {
      styles: true,
      startIndex: true,
      reversed: true
    }
  },
  placeholder: 'Type or paste your content here!',
  table: {
    contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties']
  },
  translations: [translations]
});
const editor = ref(ClassicEditor);

// 定义刷新表格emit
const emit = defineEmits(['ok']);
const dialogNewsClose = () => {
  useMessageBox()
    .confirm('修改内容可能还未保存，确定关闭吗?')
    .then(() => {
      dialogNewsVisible.value = false;
    });
};

// 公众号id
const accountId = ref();

// 文章数据
const articlesAdd = ref(
  {
    id: '',
    title: '',
    articleType: '1',
    cap: '',
    deptName: '',
    author: '',
    brief: '',
    content: '',
    official: '',
    app: '',
    createBy: '',
    createTime: ''

  },
);

// 激活文章
const isActiveAddNews = ref(0);
// 编辑媒体的id
const articlesMediaId = ref();
const newList = reactive({
  list: [{
    str: '',
    str2: ''
  }]
}
);

const openDialog = (data: any) => {


  dialogNewsVisible.value = true;
  operateMaterial.value = 'add';

  articlesAdd.value = {
    id: '',
    title: '',
    articleType: '1',
    cap: '',
    deptName: '',
    author: '',
    brief: '',
    content: '',
    official: '',
    app: '',
    createBy: '',
    createTime: ''

  }
  isLayoutReady.value = true
  if (data) {
    operateMaterial.value = 'edit';
    articlesAdd.value.id = data
    getObj(data).then((res) => {
      console.log('getObj', res.data.article.content);
      articlesAdd.value = res.data.article
    })
  }
};

const uploadData = reactive({
  bucketName: 'homepage'
});



const openMaterial = () => {
  WxMaterialSelectRef.value.openDialog({
    type: 'image',
    accountId: accountId.value,
  });
};




const onReady = (editor => {
  editor.plugins.get("FileRepository").createUploadAdapter = loader => {
    return new MyUploadAdapter(loader);
  };
  // // 剪切板内容拦截处理
  editor.plugins.get('ClipboardPipeline').on('inputTransformation', (evt, data) => {
    let newData = data.dataTransfer.getData('text/html')
    getData(data.dataTransfer.getData('text/html')).then(() => {
      // editor.setData(() => {
      //   data.dataTransfer.getData('text/html').replaceAll('https', '111111111111111111')
      //   for (let index = 0; index < newList.list.length; index++) {
      //     data.dataTransfer.getData('text/html').replaceAll(newList.list[index].str, newList.list[index].str2)
      //   }
      // })
      // console.log('changeUrl(newList.list)', changeUrl(newList.list, newData));
      changeUrl(newList.list, newData).then((res) => {
        editor.setData(res)
        evt.cancel()
      })



    })

    // evt.cancel()
  })

})
async function changeUrl(list, newData) {
  console.log('list', list);
  console.log('newData', newData);

  for (let index = 0; index < list.length; index++) {
    console.log('list[index].str', list[index].str);
    console.log('list[index].str2', list[index].str2);

    newData = newData.replaceAll(list[index].str, list[index].str2)
  }
  console.log('替换newData', newData);
  return newData
}

async function getData(newData) {
  const RegEx = /(?<=(style="))[^"]*?(?=")/gims
  const list = newData.match(RegEx)
  for (const key in list) {
    if (list[key].includes('background-image:url')) {
      let str = list[key].substring(22, list[key].indexOf(')'))
      let str2 = str.substring(0, str.length - 1)
      let type = 'image/png'
      let fileName = 'image.png'
      if (str2.includes('.jpg?')) {
        type = 'image/jpeg'
        fileName = 'image.jpg'
      } else if (str2.includes('.png?')) {
        type = 'image/png'
        fileName = 'image.png'
      } else if (str2.includes('.svg?')) {
        type = 'image/svg+xml'
        fileName = 'image.svg'
      }
      urlToFile(str2, fileName, type).then(async file => {
        console.log('file', file);

        const data = new FormData();
        data.append('file', await file);
        data.append('bucketName', 'homepage');
        await axios({
          url: `/api/admin/sys-file/upload2`,
          headers: {
            Authorization: 'Bearer ' + Session.getToken(),
          },
          method: 'POST',
          data,
        }).then((res) => {
          newList.list.push({
            str: str2,
            str2: 'http://82.157.235.89:19999' + res.data.data.url
          })
        })
      })
    }
  }
  const RegEx2 = /(?<=(src="))[^"]*?(?=")/gims
  const list2 = newData.match(RegEx2)
  for (const key in list2) {
    let str3 = list2[key]
    let type = 'image/png'
    let fileName = 'image.png'
    if (str3.includes('.jpg?')) {
      type = 'image/jpeg'
      fileName = 'image.jpg'
    } else if (str3.includes('.png?')) {
      type = 'image/png'
      fileName = 'image.png'
    } else if (str3.includes('.svg?')) {
      type = 'image/svg+xml'
      fileName = 'image.svg'
    }
    urlToFile(str3, fileName, type).then(async file => {
      const data = new FormData();
      data.append('file', await file);
      data.append('bucketName', 'homepage');
      await axios({
        url: `/api/admin/sys-file/upload2`,
        headers: {
          Authorization: 'Bearer ' + Session.getToken(),
        },
        method: 'POST',
        data,
      }).then((res) => {
        newList.list.push({
          str: str3,
          str2: 'http://82.157.235.89:19999' + res.data.data.url
        })
      })
    })
  }

  // 异步请求走完后执行循环下面的代码
}
async function urlToFile(url, fileName, mimeType) {
  return fetch(url)
    .then(response => response.blob()) // 将响应转换为Blob
    .then(blob => new File([blob], fileName, { type: mimeType })); // 创建File对象
}
const handleImageChange = (response) => {
  articlesAdd.value.cap = response.data.url

  // articlesAdd.value[isActiveAddNews.value].thumbMediaId = response.data.mediaId;
  // articlesAdd.value[isActiveAddNews.value].thumbUrl = response.data.url;
};

const handleRemoveImageChange = (response) => {
  articlesAdd.value.cap = ''
};

const onSubmit = () => {
  console.log('articlesAdd', articlesAdd.value.content)

  // return
  addMaterialLoading.value = true;
  if (operateMaterial.value === 'add') {
    addObj(
      articlesAdd.value
    )
      .then(() => {
        addMaterialLoading.value = false;
        dialogNewsVisible.value = false;
        isActiveAddNews.value = 0;
        articlesAdd.value = {
          id: '',
          title: '',
          articleType: '',
          cap: '',
          deptName: '',
          author: '',
          brief: '',
          content: '',
          official: '',
          app: '',
          createBy: '',
          createTime: ''

        }
        emit('ok');
      })
      .finally(() => {
        addMaterialLoading.value = false;
      });
  }
  if (operateMaterial.value === 'edit') {
    addObj(
      articlesAdd.value
    )
      .then(() => {
        addMaterialLoading.value = false;
        dialogNewsVisible.value = false;
        isActiveAddNews.value = 0;
        articlesAdd.value = [
          {
            title: '',
            thumbMediaId: '',
            author: '',
            digest: '',
            showCoverPic: '',
            content: '',
            contentSourceUrl: '',
            needOpenComment: '',
            onlyFansCanComment: '',
            thumbUrl: '',
          },
        ];
        emit('ok');
      })
      .finally(() => {
        addMaterialLoading.value = false;

      });
  }
};
// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
.tree-position {
  margin: 12px 20px 0 0;
}

.pagination {
  float: right;
  margin-right: 25px;
}

.add_but {
  padding: 10px;
}

.ope-row {
  margin-top: 5px;
  text-align: center;
  border-top: 1px solid #eaeaea;
  padding-top: 5px;
}

.item-name {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

.el-upload__tip {
  margin-left: 5px;
}

/*新增图文*/
.left {
  display: inline-block;
  width: 35%;
  vertical-align: top;
  margin-top: 200px;
}

.right {
  display: inline-block;
  width: 60%;
  margin-top: -40px;
}

.avatar-uploader {
  width: 20%;
  display: inline-block;
}

.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: unset !important;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px solid #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 230px;
  height: 120px;
}

.avatar1 {
  width: 120px;
  height: 120px;
}

.digest {
  width: 80%;
  display: flex;
  align-items: center;
  display: inline-block;
  vertical-align: top;
}

/*新增图文*/
/*瀑布流样式*/
.waterfall {
  width: 100%;
  column-gap: 10px;
  column-count: 5;
  margin: 0 auto;
}

.waterfall-item {
  padding: 10px;
  margin-bottom: 10px;
  break-inside: avoid;
  border: 1px solid #eaeaea;
}

p {
  line-height: 30px;
}

@media (min-width: 992px) and (max-width: 1300px) {
  .waterfall {
    column-count: 3;
  }

  p {
    color: red;
  }
}

@media (min-width: 768px) and (max-width: 991px) {
  .waterfall {
    column-count: 2;
  }

  p {
    color: orange;
  }
}

@media (max-width: 767px) {
  .waterfall {
    column-count: 1;
  }
}

/*瀑布流样式*/
.news-main {
  background-color: #ffffff;
  width: 100%;
  margin: auto;
  height: 120px;
}

.news-content {
  background-color: #acadae;
  width: 100%;
  height: 120px;
  position: relative;
}

.news-content-title {
  display: inline-block;
  font-size: 15px;
  color: #ffffff;
  position: absolute;
  left: 0px;
  bottom: 0px;
  background-color: black;
  width: 98%;
  padding: 1%;
  opacity: 0.65;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  height: 25px;
}

.news-main-item {
  background-color: #ffffff;
  padding: 5px 0px;
  border-top: 1px solid #eaeaea;
  width: 100%;
  margin: auto;
}

.news-content-item {
  position: relative;
  margin-left: -3px;
}

.news-content-item-title {
  display: inline-block;
  font-size: 12px;
  width: 70%;
}

.news-content-item-img {
  display: inline-block;
  width: 25%;
  background-color: #acadae;
}

.input-tt {
  padding: 5px;
}

.activeAddNews {
  border: 5px solid #2bb673;
}

.news-main-plus {
  width: 280px;
  text-align: center;
  margin: auto;
  height: 50px;
}

.icon-plus {
  margin: 10px;
  font-size: 25px;
}

.select-item {
  width: 60%;
  padding: 10px;
  margin: 0 auto 10px auto;
  border: 1px solid #eaeaea;
}

.father .child {
  display: none;
  text-align: center;
  position: relative;
  bottom: 25px;
}

.father:hover .child {
  display: block;
}

.thumb-div {
  display: inline-block;
  width: 20%;
  text-align: center;
}

.thumb-but {
  display: flex;
  margin: 5px;
  justify-content: space-between;
}

.material-img {
  width: 100%;
  height: 100%;
}
</style>
